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

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 16:18:59 +02:00
co-authored by Claude Sonnet 5.5
parent 361a2974cf
commit 30132deb0e
81 changed files with 4968 additions and 115 deletions
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
/**
* Keeps the image files of stock items, which help recognise them on a
* touch screen: an upright JPEG without metadata and its thumbnail.
*/
interface StockItemImages
{
/**
* @return array{path: string, thumbnailPath: string}
*
* @throws InvalidStockImage
*/
public function store(string $uploadedFilePath, int $itemId): array;
/**
* @param list<string> $paths
*/
public function delete(array $paths): void;
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
/**
* Reads stock items, groups and movements. Other modules (machines, quick
* sales, jobs' task material) read stock through this contract.
*/
interface StockQueries
{
/**
* @return list<StockGroupSummary> 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<StockItemSummary>
*/
public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array;
public function findItem(int $id): ?StockItemSummary;
/**
* @param list<int> $ids
* @return array<int, StockItemSummary> By id.
*/
public function itemsByIds(array $ids): array;
/**
* The item's movements, newest first, with the balance after each.
*
* @return list<StockMovementSummary>
*/
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;
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A purchase (hankinta) as entered: the day (Y-m-d), the quantity, and the
* price without VAT either in total or per unit (the other left empty).
*/
final readonly class PurchaseData
{
public function __construct(
public int $itemId,
public string $occurredOn,
public string $quantity,
public string $totalPrice = '',
public string $unitPrice = '',
public ?string $supplier = null,
public ?string $documentNumber = null,
) {}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
final readonly class StockGroupSummary
{
public function __construct(
public int $id,
public string $name,
public bool $isActive,
public int $itemCount = 0,
) {}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A stock item's details as entered: the unit key and the reorder level
* as typed ("2,5"; empty for none).
*/
final readonly class StockItemData
{
public function __construct(
public int $groupId,
public string $name,
public string $unit,
public ?string $code = null,
public ?string $supplier = null,
public string $reorderLevel = '',
) {}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockUnit;
/**
* A stock item with its balance (in thousandths), moving average cost (in
* hundredths of a cent per unit) and stock value (in cents). Costs and
* values are shown only to those who may see them.
*/
final readonly class StockItemSummary
{
public function __construct(
public int $id,
public int $groupId,
public string $groupName,
public string $name,
public StockUnit $unit,
public ?string $code,
public ?string $supplier,
public ?int $reorderLevelMilli,
public int $balanceMilli,
public int $averageCostHundredths,
public int $valueCents,
public bool $hasImage,
public bool $isActive,
) {}
/**
* At or below the reorder level: to be ordered (tilattava).
*/
public function needsReorder(): bool
{
return $this->reorderLevelMilli !== null && $this->balanceMilli <= $this->reorderLevelMilli;
}
public function isNegative(): bool
{
return $this->balanceMilli < 0;
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
/**
* A stock movement in an item's history: signed quantity and the balance
* after it (in thousandths), its value in cents, when and by whom, and
* what it was for. $recordedAt is "Y-m-d H:i" in the company's time zone.
*/
final readonly class StockMovementSummary
{
public function __construct(
public int $id,
public int $itemId,
public StockMovementKind $kind,
public int $quantityMilli,
public int $balanceAfterMilli,
public int $valueCents,
public string $occurredOn,
public string $recordedAt,
public int $userId,
public string $userName,
public ?int $taskId,
public ?int $jobId,
public ?int $machineId,
public ?int $orderLineId,
public ?int $maintenanceRecordId,
public ?int $inventoryCountId,
public ?string $reason,
public ?string $supplier,
public ?string $documentNumber,
public ?int $reversesMovementId,
public ?int $reversedByMovementId,
) {}
public function canBeReversed(): bool
{
return $this->reversedByMovementId === null
&& $this->kind !== StockMovementKind::Reversal
&& $this->kind !== StockMovementKind::Adjustment;
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* Stock used (käyttö) as entered: the quantity as typed and what it was
* used for; use without a target needs a reason.
*/
final readonly class StockUseData
{
public function __construct(
public int $itemId,
public string $quantity,
public ?int $taskId = null,
public ?int $jobId = null,
public ?int $machineId = null,
public ?int $orderLineId = null,
public ?int $maintenanceRecordId = null,
public ?string $reason = null,
) {}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* Recorded use or write-off: the movement, the item's name, the quantity
* taken and the item's new balance (in thousandths).
*/
final readonly class StockUseResult
{
public function __construct(
public int $movementId,
public string $itemName,
public int $quantityMilli,
public int $balanceMilli,
) {}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Entities\StockItem;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Adds a stock item with a zero balance; stock comes in with purchases.
*/
final class AddStockItem
{
public function __construct(
private StockItemRepository $items,
private StockItemFields $fields,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws InvalidStockQuantity
* @throws StockItemGroupNotFound
* @throws StockNameTaken
*/
public function execute(StockItemData $data): int
{
$fields = $this->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();
});
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Adds a stock item group last in order.
*/
final class AddStockItemGroup
{
public function __construct(
private StockItemGroupRepository $groups,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws StockNameTaken
*/
public function execute(string $name): int
{
$name = new StockName($name);
return $this->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();
});
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Renames a stock item group, moves it one place up or down, or takes it
* out of use or back. Groups are never deleted.
*/
final class ChangeStockItemGroup
{
public function __construct(
private StockItemGroupRepository $groups,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws StockNameTaken
* @throws StockItemGroupNotFound
*/
public function rename(int $groupId, string $name): void
{
$name = new StockName($name);
$this->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);
});
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\Contracts\StockItemImages;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Sets or removes a stock item's image; the replaced files are deleted.
*/
final class ChangeStockItemImage
{
public function __construct(
private StockItemRepository $items,
private StockItemImages $images,
private TransactionManager $transactions,
) {}
/**
* @param string|null $uploadedFilePath Null removes the image.
*
* @throws StockItemNotFound
* @throws InvalidStockImage
*/
public function execute(int $itemId, ?string $uploadedFilePath): void
{
$this->items->findById($itemId) ?? throw new StockItemNotFound;
$stored = $uploadedFilePath === null ? null : $this->images->store($uploadedFilePath, $itemId);
/** @var list<string> $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);
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\PurchaseData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockCost;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockDay;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Users\Application\Contracts\Clock;
use DateTimeImmutable;
/**
* Records a purchase (hankinta): stock comes in at its price without VAT,
* given in total or per unit, and the item's moving average cost is
* updated (spec 19.2).
*/
final class RecordStockPurchase
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The movement's id.
*
* @throws StockItemNotFound
* @throws InvalidStockQuantity
* @throws InvalidStockCost
* @throws InvalidStockDay
*/
public function execute(PurchaseData $data, int $actorUserId): int
{
$quantity = StockQuantity::parsePositive($data->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;
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\DTOs\StockUseResult;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Records stock used (käyttö) today at the moving average cost, for a
* task, a machine, a quick sale order or a maintenance, or with a reason.
* Use is never refused for a low balance: a machine must not stop for the
* record, so the balance may go negative, which the stock list warns of
* (spec 19.2).
*/
final class RecordStockUse
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @throws StockItemNotFound
* @throws StockItemInactive
* @throws InvalidStockQuantity
* @throws StockReasonRequired
*/
public function execute(StockUseData $data, int $actorUserId): StockUseResult
{
$quantity = StockQuantity::parsePositive($data->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));
});
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\DTOs\StockUseResult;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Records a write-off (hävikki / poisto) with its reason, e.g. damaged or
* expired stock, or a reprint in production; possibly for a target too.
*/
final class RecordStockWriteOff
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @throws StockItemNotFound
* @throws InvalidStockQuantity
* @throws StockReasonRequired
*/
public function execute(StockUseData $data, int $actorUserId): StockUseResult
{
$quantity = StockQuantity::parsePositive($data->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));
});
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Reverses a movement (vastakirjaus): the same movement negated, referring
* to the original, recorded today. Users may reverse their own use on the
* day it was recorded; other corrections need the right to correct any
* movement (management). Reversing a purchase also takes it out of the
* moving average cost.
*/
final class ReverseStockMovement
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The reversal's id.
*
* @throws StockMovementNotFound
* @throws StockMovementNotReversible
* @throws StockMovementAlreadyReversed
* @throws StockReversalNotAllowed
*/
public function execute(int $movementId, int $actorUserId, bool $mayReverseAny): int
{
$today = $this->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();
});
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes a stock item out of use, or back. An item out of use cannot be
* used, but its movements stay.
*/
final class SetStockItemActive
{
public function __construct(
private StockItemRepository $items,
private TransactionManager $transactions,
) {}
/**
* @throws StockItemNotFound
*/
public function execute(int $itemId, bool $active): void
{
$this->transactions->run(function () use ($itemId, $active): void {
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
$active ? $item->activate() : $item->deactivate();
$this->items->save($item);
});
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
/**
* Checks a stock item's entered details, shared by adding and updating.
*/
final class StockItemFields
{
public function __construct(
private StockItemRepository $items,
private StockItemGroupRepository $groups,
) {}
/**
* @return array{name: StockName, unit: StockUnit, reorderLevelMilli: ?int}
*
* @throws InvalidStockName
* @throws InvalidStockQuantity
*/
public function parse(StockItemData $data): array
{
return [
'name' => 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;
}
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Changes a stock item's details. Its movements and balance stay.
*/
final class UpdateStockItem
{
public function __construct(
private StockItemRepository $items,
private StockItemFields $fields,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws InvalidStockQuantity
* @throws StockItemGroupNotFound
* @throws StockItemNotFound
* @throws StockNameTaken
*/
public function execute(int $itemId, StockItemData $data): void
{
$fields = $this->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);
});
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
interface StockItemGroupRepository
{
public function findById(int $id): ?StockItemGroup;
public function save(StockItemGroup $group): StockItemGroup;
public function isNameTaken(string $name, ?int $exceptId = null): bool;
public function nextSortOrder(): int;
/**
* The group just before ($up) or after it in order, if any.
*/
public function neighbour(StockItemGroup $group, bool $up): ?StockItemGroup;
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockItem;
interface StockItemRepository
{
public function findById(int $id): ?StockItem;
/**
* The item, locked until the end of the transaction, so that its
* balance and average cost change one movement at a time.
*/
public function lockById(int $id): ?StockItem;
public function save(StockItem $item): StockItem;
public function isNameTaken(string $name, ?int $exceptId = null): bool;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockMovement;
interface StockMovementRepository
{
public function add(StockMovement $movement): StockMovement;
public function findById(int $id): ?StockMovement;
public function isReversed(int $movementId): bool;
/**
* The item's balance in thousandths: the sum of its movements.
*/
public function balanceOf(int $itemId): int;
}
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
/**
* A stock item (nimike), e.g. a photo paper or an ink, counted in its unit.
* Its balance is the sum of its movements and is not kept here; the item
* keeps its moving average cost, which only purchases change. Items are
* never deleted: one taken out of use cannot be used, but its movements
* stay.
*/
final class StockItem
{
private function __construct(
private ?int $id,
private int $groupId,
private StockName $name,
private StockUnit $unit,
private ?string $code,
private ?string $supplier,
private ?int $reorderLevelMilli,
private int $averageCostHundredths,
private ?string $imagePath,
private ?string $thumbnailPath,
private bool $active,
) {}
public static function create(int $groupId, StockName $name, StockUnit $unit, ?string $code, ?string $supplier, ?int $reorderLevelMilli): self
{
return new self(null, $groupId, $name, $unit, self::text($code), self::text($supplier), $reorderLevelMilli, 0, null, null, true);
}
public static function reconstitute(
int $id,
int $groupId,
StockName $name,
StockUnit $unit,
?string $code,
?string $supplier,
?int $reorderLevelMilli,
int $averageCostHundredths,
?string $imagePath,
?string $thumbnailPath,
bool $active,
): self {
return new self($id, $groupId, $name, $unit, $code, $supplier, $reorderLevelMilli, $averageCostHundredths, $imagePath, $thumbnailPath, $active);
}
public function change(int $groupId, StockName $name, StockUnit $unit, ?string $code, ?string $supplier, ?int $reorderLevelMilli): void
{
$this->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);
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
/**
* A group of stock items (nimikeryhmä), e.g. Paperit ja kartongit. Groups
* are ordered, and never deleted, only taken out of use.
*/
final class StockItemGroup
{
private function __construct(
private ?int $id,
private StockName $name,
private int $sortOrder,
private bool $active,
) {}
public static function create(StockName $name, int $sortOrder): self
{
return new self(null, $name, $sortOrder, true);
}
public static function reconstitute(int $id, StockName $name, int $sortOrder, bool $active): self
{
return new self($id, $name, $sortOrder, $active);
}
public function rename(StockName $name): void
{
$this->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;
}
}
@@ -0,0 +1,225 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use DateTimeImmutable;
/**
* A change in an item's balance (varastotapahtuma, spec 19.2). Movements
* are never changed or deleted: a mistake is corrected with a reversal,
* the same movement negated, which refers to the original. The quantity
* is signed (in thousandths) and the value is at the unit cost of the
* moment: the purchase price for a purchase, the moving average cost
* otherwise.
*/
final class StockMovement
{
private function __construct(
private ?int $id,
private int $itemId,
private StockMovementKind $kind,
private int $quantityMilli,
private int $unitCostHundredths,
private int $valueCents,
private DateTimeImmutable $occurredOn,
private DateTimeImmutable $recordedAt,
private int $userId,
private ?StockUseTarget $target,
private ?string $reason,
private ?string $supplier,
private ?string $documentNumber,
private ?int $inventoryCountId,
private ?int $reversesMovementId,
) {}
public static function purchase(StockItem $item, StockQuantity $quantity, int $valueCents, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId, ?string $supplier, ?string $documentNumber): self
{
return new self(
null, (int) $item->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);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Enums;
/**
* What a stock movement is (spec 19.2): a purchase adds stock, use and a
* write-off take it, a stock count adjusts it either way, and a reversal
* cancels an earlier movement with the opposite quantity.
*/
enum StockMovementKind: string
{
case Purchase = 'purchase';
case Consumption = 'consumption';
case WriteOff = 'write_off';
case Adjustment = 'adjustment';
case Reversal = 'reversal';
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Enums;
/**
* The unit a stock item is counted in (spec 19.1). Labels are in
* lang/*\/inventory.php under units.
*/
enum StockUnit: string
{
case Piece = 'piece';
case Sheet = 'sheet';
case Roll = 'roll';
case Metre = 'metre';
case SquareMetre = 'square_metre';
case Litre = 'litre';
case Package = 'package';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockCost extends DomainException
{
public function __construct()
{
parent::__construct('A purchase price must be zero or more, with at most four decimals for a unit price.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockDay extends DomainException
{
public function __construct()
{
parent::__construct('The day must be a valid date.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockImage extends DomainException
{
public function __construct()
{
parent::__construct('The file is not a supported image.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockName extends DomainException
{
public function __construct()
{
parent::__construct('A stock name must be 1-150 characters.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockQuantity extends DomainException
{
public function __construct()
{
parent::__construct('A stock quantity must be a number with at most three decimals.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockItemGroupNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The stock item group was not found.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockItemInactive extends DomainException
{
public function __construct()
{
parent::__construct('The stock item is no longer in use.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockItemNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The stock item was not found.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockMovementAlreadyReversed extends DomainException
{
public function __construct()
{
parent::__construct('The stock movement has already been reversed.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockMovementNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The stock movement was not found.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockMovementNotReversible extends DomainException
{
public function __construct()
{
parent::__construct('Reversals and stock count adjustments cannot be reversed.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockNameTaken extends DomainException
{
public function __construct()
{
parent::__construct('The name is already in use.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockReasonRequired extends DomainException
{
public function __construct()
{
parent::__construct('A reason is required.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockReversalNotAllowed extends DomainException
{
public function __construct()
{
parent::__construct('Only your own use recorded today may be reversed.');
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Services;
/**
* Matches stock items to a search typed on a keyboard or touch screen, or
* read by a barcode scanner: every word of the search must be found in the
* name or the code, regardless of case and of the dots of å, ä and ö
* (spec 19.6).
*/
final class StockSearch
{
public static function matches(string $search, string $name, ?string $code): bool
{
$words = preg_split('/\s+/u', self::normalize($search), -1, PREG_SPLIT_NO_EMPTY) ?: [];
$haystack = self::normalize($name.' '.($code ?? ''));
foreach ($words as $word) {
if (! str_contains($haystack, $word)) {
return false;
}
}
return true;
}
public static function normalize(string $value): string
{
return strtr(mb_strtolower(trim($value)), ['å' => 'a', 'ä' => 'a', 'ö' => 'o', 'é' => 'e', 'ü' => 'u']);
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Services;
/**
* Valuation of stock at a moving average cost (liukuva keskihinta, spec
* 19.2). Unit costs are in hundredths of a cent per whole unit, so that
* cheap units such as a millilitre of ink keep their precision; values
* are in cents, rounded half away from zero.
*/
final class StockValuation
{
/**
* The value of a quantity (in thousandths) at a unit cost.
*/
public static function valueCents(int $quantityMilli, int $unitCostHundredths): int
{
return self::divideRounded($quantityMilli * $unitCostHundredths, 100_000);
}
/**
* The unit cost of a purchase of a quantity for a total value.
*/
public static function unitCostOf(int $quantityMilli, int $valueCents): int
{
return $quantityMilli === 0 ? 0 : self::divideRounded($valueCents * 100_000, $quantityMilli);
}
/**
* The average unit cost after a purchase: (old balance × old average +
* purchase value) / new balance. When the stock before was empty or
* negative, or nothing is left after, the purchase's own unit cost.
*/
public static function averageAfterPurchase(int $balanceMilli, int $averageHundredths, int $purchasedMilli, int $purchaseValueCents): int
{
$newBalance = $balanceMilli + $purchasedMilli;
if ($balanceMilli <= 0 || $newBalance <= 0) {
return max(0, self::unitCostOf($purchasedMilli, $purchaseValueCents));
}
$oldValueHundredthsMilli = $balanceMilli * $averageHundredths;
return max(0, self::divideRounded($oldValueHundredthsMilli + $purchaseValueCents * 100_000, $newBalance));
}
private static function divideRounded(int $dividend, int $divisor): int
{
$sign = ($dividend < 0) !== ($divisor < 0) ? -1 : 1;
$dividend = abs($dividend);
$divisor = abs($divisor);
return $sign * intdiv($dividend + intdiv($divisor, 2), $divisor);
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\ValueObjects;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
/**
* Name of a stock item or an item group, e.g. "Valokuvapaperi 10×15".
*/
final readonly class StockName
{
public const int MAX_LENGTH = 150;
public string $value;
/**
* @throws InvalidStockName
*/
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidStockName;
}
$this->value = $value;
}
}
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\ValueObjects;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
/**
* A quantity of stock in thousandths of the item's unit (e.g. 2,5 m² =
* 2500), so three decimals are kept exactly. Typed in as "2,5", "2.5" or
* "1 200".
*/
final readonly class StockQuantity
{
public const int MAX_MILLI = 9_999_999_999;
private function __construct(public int $milli) {}
/**
* @throws InvalidStockQuantity
*/
public static function ofMilli(int $milli): self
{
if (abs($milli) > 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));
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\ValueObjects;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
/**
* What stock was used for (spec 19.2): a job's task, a machine, a quick
* sale order line or a machine's maintenance, each possibly with a reason.
* Use without a target (e.g. a test run) needs a reason.
*/
final readonly class StockUseTarget
{
public ?string $reason;
/**
* @throws StockReasonRequired
*/
public function __construct(
public ?int $taskId = null,
public ?int $jobId = null,
public ?int $machineId = null,
public ?int $orderLineId = null,
public ?int $maintenanceRecordId = null,
?string $reason = null,
) {
$reason = $reason === null ? null : trim($reason);
$this->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);
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Files;
use App\Modules\Inventory\Application\Contracts\StockItemImages;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
use App\Modules\Shared\Application\Contracts\ImageResizer;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
/**
* Stock item images on the private local disk under stock-items/: an
* upright JPEG without metadata and a thumbnail for touch-screen buttons.
*/
class StockItemImageFiles implements StockItemImages
{
public const string DISK = 'local';
public const int MAX_SIZE = 1280;
public const int THUMBNAIL_SIZE = 240;
public function __construct(private ImageResizer $resizer) {}
public function store(string $uploadedFilePath, int $itemId): array
{
$versions = $this->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);
}
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Eloquent;
use Database\Factories\StockItemGroupFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Persistence model, used only inside the Inventory Infrastructure layer.
*
* @property int $id
* @property string $name
* @property int $sort_order
* @property bool $is_active
*/
#[Table('stock_item_groups')]
#[Fillable(['name', 'sort_order', 'is_active'])]
#[UseFactory(StockItemGroupFactory::class)]
class StockItemGroupModel extends Model
{
/** @use HasFactory<StockItemGroupFactory> */
use HasFactory;
/**
* @return HasMany<StockItemModel, $this>
*/
public function items(): HasMany
{
return $this->hasMany(StockItemModel::class, 'stock_item_group_id');
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'sort_order' => 'integer',
'is_active' => 'boolean',
];
}
}
@@ -0,0 +1,60 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Eloquent;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use Database\Factories\StockItemFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Persistence model, used only inside the Inventory Infrastructure layer.
*
* @property int $id
* @property int $stock_item_group_id
* @property string $name
* @property StockUnit $unit
* @property string|null $code
* @property string|null $supplier
* @property int|null $reorder_level_milli
* @property int $average_cost_hundredths
* @property string|null $image_path
* @property string|null $thumbnail_path
* @property bool $is_active
* @property int|null $balance_milli Selected sum of the movements.
*/
#[Table('stock_items')]
#[Fillable(['stock_item_group_id', 'name', 'unit', 'code', 'supplier', 'reorder_level_milli', 'average_cost_hundredths', 'image_path', 'thumbnail_path', 'is_active'])]
#[UseFactory(StockItemFactory::class)]
class StockItemModel extends Model
{
/** @use HasFactory<StockItemFactory> */
use HasFactory;
/**
* @return BelongsTo<StockItemGroupModel, $this>
*/
public function group(): BelongsTo
{
return $this->belongsTo(StockItemGroupModel::class, 'stock_item_group_id');
}
/**
* @return array<string, string>
*/
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',
];
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Eloquent;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Carbon;
/**
* Persistence model, used only inside the Inventory Infrastructure layer.
*
* @property int $id
* @property int $stock_item_id
* @property StockMovementKind $kind
* @property int $quantity_milli
* @property int $unit_cost_hundredths
* @property int $value_cents
* @property Carbon $occurred_on
* @property Carbon $recorded_at
* @property int $user_id
* @property int|null $task_id
* @property int|null $customer_job_id
* @property int|null $machine_id
* @property int|null $quick_sale_order_line_id
* @property int|null $maintenance_record_id
* @property int|null $inventory_count_id
* @property int|null $reverses_movement_id
* @property string|null $reason
* @property string|null $supplier
* @property string|null $document_number
*/
#[Table('stock_movements')]
#[Fillable([
'stock_item_id', 'kind', 'quantity_milli', 'unit_cost_hundredths', 'value_cents', 'occurred_on', 'recorded_at', 'user_id',
'task_id', 'customer_job_id', 'machine_id', 'quick_sale_order_line_id', 'maintenance_record_id', 'inventory_count_id',
'reverses_movement_id', 'reason', 'supplier', 'document_number',
])]
class StockMovementModel extends Model
{
/**
* @return HasOne<StockMovementModel, $this>
*/
public function reversal(): HasOne
{
return $this->hasOne(StockMovementModel::class, 'reverses_movement_id');
}
/**
* @return array<string, string>
*/
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',
];
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
class EloquentStockItemGroupRepository implements StockItemGroupRepository
{
public function findById(int $id): ?StockItemGroup
{
$model = StockItemGroupModel::query()->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);
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Entities\StockItem;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
class EloquentStockItemRepository implements StockItemRepository
{
public function findById(int $id): ?StockItem
{
$model = StockItemModel::query()->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,
);
}
}
@@ -0,0 +1,81 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use DateTimeImmutable;
class EloquentStockMovementRepository implements StockMovementRepository
{
public function add(StockMovement $movement): StockMovement
{
$target = $movement->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,
);
}
}
@@ -0,0 +1,185 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
use App\Modules\Inventory\Domain\Services\StockSearch;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class EloquentStockQueries implements StockQueries
{
public function __construct(private UserAccountQueries $users) {}
public function groups(bool $includeInactive = true): array
{
return StockItemGroupModel::query()
->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<StockItemModel>
*/
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<int, StockMovementModel> $models Newest first.
* @param int $balance The balance after the newest of them.
* @return list<StockMovementSummary>
*/
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;
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Inventory\Application\Contracts\StockItemImages;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Infrastructure\Files\StockItemImageFiles;
use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemGroupRepository;
use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemRepository;
use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockMovementRepository;
use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockQueries;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Inventory module (stock items, movements and stock counts,
* spec 19.1–19.3) into Laravel: bindings, routes, the `inventory::`
* Livewire namespace and the `inventory.*` abilities (spec 19.9).
*/
class InventoryServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
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() !== []);
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Modules\Inventory\Presentation\Http\Controllers;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
/**
* A stock item's image or its thumbnail from the private disk, to those who
* see the stock.
*/
class ShowStockItemImage
{
public function __invoke(int $item, string $size, StockQueries $stock): Response
{
Gate::authorize('inventory.view');
$path = $stock->imagePathOf($item, $size === 'thumbnail') ?? abort(404);
$disk = Storage::disk('local');
abort_unless($disk->exists($path), 404);
return $disk->response($path, basename($path), ['Content-Type' => 'image/jpeg', 'Cache-Control' => 'private, max-age=86400']);
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Modules\Inventory\Presentation\Livewire\Concerns;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Shared\Domain\ValueObjects\Money;
use Carbon\CarbonImmutable;
/**
* Formatting shared by the stock pages and the components that show stock
* elsewhere (task material, machine console). Values may be negative.
*/
trait FormatsStock
{
public function quantity(int $milli, StockUnit|string|null $unit = null): string
{
$unitKey = $unit instanceof StockUnit ? $unit->value : $unit;
return StockQuantity::format($milli).($unitKey === null ? '' : "\u{00A0}".__('inventory.units.'.$unitKey));
}
public function money(int $cents): string
{
return ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format();
}
/**
* A unit cost in hundredths of a cent, e.g. "0,0123 €" or "12,50 €".
*/
public function unitCost(int $hundredths): string
{
$euros = number_format($hundredths / 10_000, 4, ',', "\u{00A0}");
$euros = preg_replace('/(,\d\d)00$/', '$1', $euros) ?? $euros;
$euros = preg_replace('/(,\d\d\d)0$/', '$1', $euros) ?? $euros;
return $euros."\u{00A0}€";
}
/**
* "24.11.2026" for "2026-11-24"; "24.11.2026 klo 14.05" for "2026-11-24 14:05".
*/
public function dateLabel(string $value): string
{
return strlen($value) > 10
? CarbonImmutable::createFromFormat('Y-m-d H:i', $value)->format('j.n.Y \k\l\o H.i')
: CarbonImmutable::createFromFormat('!Y-m-d', $value)->format('j.n.Y');
}
}
@@ -0,0 +1,212 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\UseCases\AddStockItemGroup;
use App\Modules\Inventory\Application\UseCases\ChangeStockItemGroup;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Stock item groups (nimikeryhmät, spec 19.1): adding, renaming, ordering
* with Move up / Move down and taking out of use. Management only.
*/
new class extends Component
{
public string $newName = '';
#[Locked]
public ?int $editingId = null;
public string $editingName = '';
#[Locked]
public string $message = '';
public function mount(): void
{
$this->authorize('inventory.manage');
}
/**
* @return list<StockGroupSummary>
*/
#[Computed]
public function groups(): array
{
return app(StockQueries::class)->groups();
}
public function add(AddStockItemGroup $addGroup): void
{
$this->authorize('inventory.manage');
try {
$addGroup->execute($this->newName);
} catch (InvalidStockName) {
$this->addError('newName', __('inventory.errors.name'));
return;
} catch (StockNameTaken) {
$this->addError('newName', __('inventory.errors.name_taken'));
return;
}
$this->message = __('inventory.groups.added', ['name' => trim($this->newName)]);
$this->newName = '';
unset($this->groups);
$this->js("document.getElementById('new-group-name')?.focus()");
}
public function startRename(int $groupId): void
{
$this->authorize('inventory.manage');
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
$this->editingId = $group->id;
$this->editingName = $group->name;
$this->resetErrorBag();
$this->js("setTimeout(() => document.getElementById('rename-group')?.focus())");
}
public function cancelRename(): void
{
$id = $this->editingId;
$this->editingId = null;
$this->js("document.getElementById('rename-group-{$id}')?.focus()");
}
public function rename(ChangeStockItemGroup $change): void
{
$this->authorize('inventory.manage');
try {
$change->rename((int) $this->editingId, $this->editingName);
} catch (InvalidStockName) {
$this->addError('editingName', __('inventory.errors.name'));
return;
} catch (StockNameTaken) {
$this->addError('editingName', __('inventory.errors.name_taken'));
return;
} catch (StockItemGroupNotFound) {
$this->message = __('inventory.errors.not_found');
}
$id = $this->editingId;
$this->message = __('inventory.groups.renamed', ['name' => trim($this->editingName)]);
$this->editingId = null;
unset($this->groups);
$this->js("document.getElementById('rename-group-{$id}')?.focus()");
}
public function move(int $groupId, string $direction, ChangeStockItemGroup $change): void
{
$this->authorize('inventory.manage');
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
$up = $direction === 'up';
try {
$moved = $change->move($groupId, $up);
} catch (StockItemGroupNotFound) {
$this->message = __('inventory.errors.not_found');
return;
}
$this->message = __('inventory.groups.'.($moved ? ($up ? 'moved_up' : 'moved_down') : ($up ? 'first' : 'last')), ['name' => $group->name]);
unset($this->groups);
}
public function toggleActive(int $groupId, ChangeStockItemGroup $change): void
{
$this->authorize('inventory.manage');
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
try {
$change->setActive($groupId, ! $group->isActive);
} catch (StockItemGroupNotFound) {
$this->message = __('inventory.errors.not_found');
return;
}
$this->message = __($group->isActive ? 'inventory.groups.deactivated' : 'inventory.groups.activated', ['name' => $group->name]);
unset($this->groups);
}
public function render(): mixed
{
return $this->view()->title(__('inventory.groups.title'));
}
};
?>
<div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('inventory.groups.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.groups.intro') }}</p>
<p class="text-sm"><x-link :href="route('inventory.index')" navigate>{{ __('inventory.groups.back') }}</x-link></p>
</div>
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $message }}</p>
<form wire:submit="add" class="flex flex-wrap items-end gap-3" novalidate>
<div class="min-w-0 flex-1">
<x-input id="new-group-name" wire:model="newName" :label="__('inventory.groups.name')" autocomplete="off" maxlength="150" />
</div>
<x-button submit icon="plus" :text="__('inventory.groups.add')" />
</form>
@if ($this->groups === [])
<p class="text-sm">{{ __('inventory.groups.none') }}</p>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-300 dark:divide-zinc-700 dark:border-zinc-600">
@foreach ($this->groups as $group)
<li wire:key="group-{{ $group->id }}" class="flex flex-wrap items-center gap-3 p-3">
@if ($editingId === $group->id)
<form wire:submit="rename" class="flex w-full flex-wrap items-end gap-2" novalidate>
<div class="min-w-0 flex-1">
<x-input id="rename-group" wire:model="editingName" :label="__('inventory.groups.name')" autocomplete="off" maxlength="150" />
</div>
<x-button submit :text="__('inventory.groups.save')" />
<x-button wire:click="cancelRename" subtle color="black" :text="__('inventory.groups.cancel')" />
</form>
@else
<div class="min-w-0 flex-1">
<p class="font-medium break-words">{{ $group->name }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
{{ trans_choice('inventory.groups.items', $group->itemCount, ['count' => $group->itemCount]) }}
@unless ($group->isActive)
· {{ __('inventory.status.inactive') }}
@endunless
</p>
</div>
<div class="flex flex-wrap gap-1">
<x-button wire:click="move({{ $group->id }}, 'up')" subtle color="black" sm icon="arrow-up" :aria-label="__('inventory.groups.up_named', ['name' => $group->name])" />
<x-button wire:click="move({{ $group->id }}, 'down')" subtle color="black" sm icon="arrow-down" :aria-label="__('inventory.groups.down_named', ['name' => $group->name])" />
<x-button id="rename-group-{{ $group->id }}" wire:click="startRename({{ $group->id }})" subtle color="black" sm icon="pencil" :text="__('inventory.groups.rename')" :aria-label="__('inventory.groups.rename_named', ['name' => $group->name])" />
<x-button
wire:click="toggleActive({{ $group->id }})"
subtle
color="black"
sm
:icon="$group->isActive ? 'archive-box-x-mark' : 'archive-box-arrow-down'"
:text="$group->isActive ? __('inventory.groups.deactivate') : __('inventory.groups.activate')"
:aria-label="__($group->isActive ? 'inventory.groups.deactivate_named' : 'inventory.groups.activate_named', ['name' => $group->name])"
/>
</div>
@endif
</li>
@endforeach
</ul>
@endif
</div>
@@ -0,0 +1,169 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* The stock list (spec 19.1): items with their balances, searched by name
* or code and filtered by group and "only items to order". Management also
* sees the average costs and the stock value.
*/
new class extends Component
{
use FormatsStock;
#[Url(as: 'haku', except: '')]
public string $search = '';
#[Url(as: 'ryhma', except: '')]
public string $group = '';
#[Url(as: 'tilattavat', except: false)]
public bool $onlyReorder = false;
public bool $includeInactive = false;
public function mount(): void
{
$this->authorize('inventory.view');
}
/**
* @return list<StockItemSummary>
*/
#[Computed]
public function items(): array
{
return app(StockQueries::class)->items(
$this->search,
$this->group === '' ? null : (int) $this->group,
$this->onlyReorder,
$this->includeInactive && Gate::allows('inventory.manage'),
);
}
/**
* @return list<StockGroupSummary>
*/
#[Computed]
public function groups(): array
{
return app(StockQueries::class)->groups(includeInactive: false);
}
public function updated(): void
{
$this->authorize('inventory.view');
unset($this->items);
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function headers(): array
{
$headers = [
['index' => 'name', 'label' => __('inventory.columns.name'), 'sortable' => false],
['index' => 'group', 'label' => __('inventory.columns.group'), 'sortable' => false],
['index' => 'balance', 'label' => __('inventory.columns.balance'), 'sortable' => false, 'align' => 'right'],
['index' => 'reorder', 'label' => __('inventory.columns.reorder_level'), 'sortable' => false, 'align' => 'right'],
['index' => 'status', 'label' => __('inventory.columns.status'), 'sortable' => false],
];
if (Gate::allows('inventory.see-value')) {
$headers[] = ['index' => 'cost', 'label' => __('inventory.columns.average_cost'), 'sortable' => false, 'align' => 'right'];
$headers[] = ['index' => 'value', 'label' => __('inventory.columns.value'), 'sortable' => false, 'align' => 'right'];
}
return $headers;
}
public function render(): mixed
{
return $this->view()->title(__('inventory.index.title'));
}
};
?>
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('inventory.index.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.index.intro') }}</p>
@can('inventory.manage')
<div class="flex flex-wrap gap-3">
<x-button :href="route('inventory.items.create')" wire:navigate icon="plus" :text="__('inventory.index.new_item')" />
<x-button :href="route('inventory.groups')" wire:navigate subtle color="black" icon="folder" :text="__('inventory.index.groups')" />
</div>
@endcan
</div>
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<x-input id="stock-search" wire:model.live.debounce.300ms="search" type="search" icon="magnifying-glass" :label="__('inventory.index.search')" autocomplete="off" />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native id="stock-group" wire:model.live="group" :label="__('inventory.index.group')" :aria-label="__('inventory.index.group')">
<option value="">{{ __('inventory.index.all_groups') }}</option>
@foreach ($this->groups as $option)
<option value="{{ $option->id }}">{{ $option->name }}</option>
@endforeach
</x-select.native>
<div class="flex flex-col justify-end gap-2">
<x-checkbox id="only-reorder" wire:model.live="onlyReorder" :label="__('inventory.index.only_reorder')" />
@can('inventory.manage')
<x-checkbox id="include-inactive" wire:model.live="includeInactive" :label="__('inventory.index.include_inactive')" />
@endcan
</div>
</div>
<p role="status" aria-live="polite" class="text-sm font-medium">
{{ trans_choice('inventory.index.count', count($this->items), ['count' => count($this->items)]) }}
</p>
@if ($this->items === [])
<p class="text-sm">{{ __('inventory.index.none') }}</p>
@else
<x-table :headers="$this->headers()" :rows="$this->items">
@interact('column_name', $item)
<x-link :href="route('inventory.items.show', $item->id)" navigate class="whitespace-normal">{{ $item->name }}</x-link>
@if ($item->code !== null)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $item->code }}</span>
@endif
@endinteract
@interact('column_group', $item)
<span class="whitespace-normal">{{ $item->groupName }}</span>
@endinteract
@interact('column_balance', $item)
<span class="whitespace-nowrap">{{ $this->quantity($item->balanceMilli, $item->unit) }}</span>
@endinteract
@interact('column_reorder', $item)
<span class="whitespace-nowrap">{{ $item->reorderLevelMilli === null ? '–' : $this->quantity($item->reorderLevelMilli, $item->unit) }}</span>
@endinteract
@interact('column_status', $item)
<x-inventory.stock-status :item="$item" />
@endinteract
@interact('column_cost', $item)
<span class="whitespace-nowrap">{{ $this->unitCost($item->averageCostHundredths) }}</span>
@endinteract
@interact('column_value', $item)
<span class="whitespace-nowrap">{{ $this->money($item->valueCents) }}</span>
@endinteract
</x-table>
@can('inventory.see-value')
<p class="text-right font-semibold">{{ __('inventory.index.total_value', ['value' => $this->money(array_sum(array_map(fn ($item) => $item->valueCents, $this->items)))]) }}</p>
@endcan
@endif
</div>
@@ -0,0 +1,227 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Application\UseCases\AddStockItem;
use App\Modules\Inventory\Application\UseCases\ChangeStockItemImage;
use App\Modules\Inventory\Application\UseCases\UpdateStockItem;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\WithFileUploads;
/**
* Add page (no {item}) and edit page (with {item}) of a stock item: group,
* name, unit, code, supplier, reorder level and an optional image.
* Management only.
*/
new class extends Component
{
use WithFileUploads;
public const int MAX_KILOBYTES = 12288;
#[Locked]
public ?int $itemId = null;
#[Locked]
public bool $hasImage = false;
public string $groupId = '';
public string $name = '';
public string $unit = 'piece';
public string $code = '';
public string $supplier = '';
public string $reorderLevel = '';
/**
* @var TemporaryUploadedFile|null
*/
public $image = null;
public bool $removeImage = false;
public function mount(StockQueries $stock, ?int $item = null): void
{
$this->authorize('inventory.manage');
if ($item === null) {
$this->groupId = (string) ($this->groups[0]->id ?? '');
return;
}
$summary = $stock->findItem($item) ?? abort(404);
$this->itemId = $summary->id;
$this->groupId = (string) $summary->groupId;
$this->name = $summary->name;
$this->unit = $summary->unit->value;
$this->code = (string) $summary->code;
$this->supplier = (string) $summary->supplier;
$this->reorderLevel = $summary->reorderLevelMilli === null ? '' : StockQuantity::inputValue($summary->reorderLevelMilli);
$this->hasImage = $summary->hasImage;
}
/**
* Groups in use, and the item's own group even when out of use.
*
* @return list<StockGroupSummary>
*/
#[Computed]
public function groups(): array
{
return array_values(array_filter(
app(StockQueries::class)->groups(),
fn (StockGroupSummary $group): bool => $group->isActive || (string) $group->id === $this->groupId,
));
}
public function save(AddStockItem $addItem, UpdateStockItem $updateItem, ChangeStockItemImage $changeImage): void
{
$this->authorize('inventory.manage');
$this->resetErrorBag();
$this->validate(
[
'groupId' => ['required', 'integer'],
'unit' => ['required', 'in:'.implode(',', array_column(StockUnit::cases(), 'value'))],
'image' => ['nullable', 'file', 'image', 'mimes:jpg,jpeg,png,webp,gif', 'max:'.self::MAX_KILOBYTES],
],
[
'groupId.required' => __('inventory.errors.group'),
'groupId.integer' => __('inventory.errors.group'),
'image.file' => __('inventory.errors.image'),
'image.image' => __('inventory.errors.image'),
'image.mimes' => __('inventory.errors.image'),
'image.max' => __('inventory.errors.image_too_large', ['size' => self::MAX_KILOBYTES / 1024]),
],
);
$data = new StockItemData((int) $this->groupId, $this->name, $this->unit, $this->code, $this->supplier, $this->reorderLevel);
try {
if ($this->itemId === null) {
$this->itemId = $addItem->execute($data);
$status = __('inventory.form.created', ['name' => trim($this->name)]);
} else {
$updateItem->execute($this->itemId, $data);
$status = __('inventory.form.updated', ['name' => trim($this->name)]);
}
if ($this->image instanceof TemporaryUploadedFile) {
$changeImage->execute($this->itemId, (string) $this->image->getRealPath());
} elseif ($this->removeImage) {
$changeImage->execute($this->itemId, null);
}
} catch (InvalidStockName) {
$this->addError('name', __('inventory.errors.name'));
return;
} catch (StockNameTaken) {
$this->addError('name', __('inventory.errors.name_taken'));
return;
} catch (InvalidStockQuantity) {
$this->addError('reorderLevel', __('inventory.errors.reorder_level'));
return;
} catch (StockItemGroupNotFound) {
$this->addError('groupId', __('inventory.errors.group'));
return;
} catch (InvalidStockImage) {
$this->addError('image', __('inventory.errors.image'));
return;
} catch (StockItemNotFound) {
abort(404);
}
session()->flash('status', $status);
$this->redirectRoute('inventory.items.show', $this->itemId, navigate: true);
}
public function heading(): string
{
return __($this->itemId === null ? 'inventory.form.create_title' : 'inventory.form.edit_title');
}
public function render(): mixed
{
return $this->view()->title($this->heading());
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
@if ($this->groups === [])
<p class="text-sm">{{ __('inventory.form.no_groups') }} <x-link :href="route('inventory.groups')" navigate>{{ __('inventory.index.groups') }}</x-link></p>
@else
<form wire:submit="save" class="space-y-6" novalidate>
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native id="item-group" wire:model="groupId" :label="__('inventory.form.group')" :aria-label="__('inventory.form.group')">
@foreach ($this->groups as $group)
<option value="{{ $group->id }}">{{ $group->name }}</option>
@endforeach
</x-select.native>
<x-input id="item-name" wire:model="name" :label="__('inventory.form.name')" autocomplete="off" maxlength="150" required />
<x-select.native id="item-unit" wire:model="unit" :label="__('inventory.form.unit')" :aria-label="__('inventory.form.unit')">
@foreach (StockUnit::cases() as $option)
<option value="{{ $option->value }}">{{ __('inventory.units.'.$option->value) }}</option>
@endforeach
</x-select.native>
<x-input id="item-code" wire:model="code" :label="__('inventory.form.code')" :hint="__('inventory.form.code_hint')" autocomplete="off" maxlength="150" />
<x-input id="item-supplier" wire:model="supplier" :label="__('inventory.form.supplier')" autocomplete="off" maxlength="150" />
<x-input id="item-reorder" wire:model="reorderLevel" inputmode="decimal" :label="__('inventory.form.reorder_level')" :hint="__('inventory.form.reorder_level_hint')" autocomplete="off" />
<div class="space-y-2">
<label for="item-image" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">{{ __('inventory.form.image') }}</label>
<p id="item-image-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.form.image_hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}</p>
@if ($hasImage && $itemId !== null)
<img src="{{ route('inventory.items.image', [$itemId, 'thumbnail']) }}" alt="{{ __('inventory.form.current_image') }}" class="size-24 rounded-md border border-zinc-300 object-cover dark:border-zinc-600" />
<x-checkbox id="remove-image" wire:model="removeImage" :label="__('inventory.form.remove_image')" />
@endif
<input
type="file"
id="item-image"
wire:model="image"
accept="image/jpeg,image/png,image/webp,image/gif"
aria-describedby="item-image-hint @error('image') item-image-error @enderror"
@error('image') aria-invalid="true" @enderror
class="block w-full max-w-md rounded-md text-sm text-zinc-900 file:me-3 file:min-h-9 file:cursor-pointer file:rounded-md file:border-0 file:bg-zinc-200 file:px-3 file:py-2 file:font-medium file:text-zinc-900 hover:file:bg-zinc-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-zinc-100 dark:file:bg-zinc-700 dark:file:text-zinc-100 dark:hover:file:bg-zinc-600 dark:focus-visible:outline-blue-400"
/>
@error('image')
<p id="item-image-error" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</div>
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('inventory.form.save')" />
<x-button :href="$itemId === null ? route('inventory.index') : route('inventory.items.show', $itemId)" wire:navigate subtle color="black" :text="__('inventory.form.cancel')" />
</div>
</form>
@endif
</div>
@@ -0,0 +1,522 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\PurchaseData;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\UseCases\RecordStockPurchase;
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
use App\Modules\Inventory\Application\UseCases\RecordStockWriteOff;
use App\Modules\Inventory\Application\UseCases\ReverseStockMovement;
use App\Modules\Inventory\Application\UseCases\SetStockItemActive;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockCost;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockDay;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* A stock item's page (spec 19.1–19.2): its details and balance, the
* movement history with the balance after each, and the forms to record a
* purchase or a write-off (management) and use without a target (everyone
* using stock). Movements are corrected with reversals.
*/
new class extends Component
{
use FormatsStock;
public const int HISTORY_LIMIT = 200;
#[Locked]
public int $itemId;
#[Locked]
public string $message = '';
#[Locked]
public ?int $reverseMovementId = null;
public string $purchaseDay = '';
public string $purchaseQuantity = '';
public string $purchaseTotal = '';
public string $purchaseUnitPrice = '';
public string $purchaseSupplier = '';
public string $purchaseDocument = '';
public string $writeOffQuantity = '';
public string $writeOffReason = '';
public string $useQuantity = '';
public string $useReason = '';
public function mount(StockQueries $stock, Clock $clock, int $item): void
{
$this->authorize('inventory.view');
$summary = $stock->findItem($item) ?? abort(404);
$this->itemId = $summary->id;
$this->purchaseDay = $clock->today()->format('Y-m-d');
$this->purchaseSupplier = (string) $summary->supplier;
$this->message = (string) session('status', '');
}
#[Computed]
public function item(): StockItemSummary
{
return app(StockQueries::class)->findItem($this->itemId) ?? abort(404);
}
/**
* @return list<StockMovementSummary>
*/
#[Computed]
public function movements(): array
{
return app(StockQueries::class)->movementsOf($this->itemId, self::HISTORY_LIMIT);
}
public function recordPurchase(RecordStockPurchase $recordPurchase): void
{
$this->authorize('inventory.manage');
$this->resetErrorBag();
if (trim($this->purchaseTotal) === '' && trim($this->purchaseUnitPrice) === '') {
$this->addError('purchaseTotal', __('inventory.errors.price_required'));
return;
}
try {
$recordPurchase->execute(new PurchaseData(
$this->itemId,
$this->purchaseDay,
$this->purchaseQuantity,
$this->purchaseTotal,
$this->purchaseUnitPrice,
$this->purchaseSupplier,
$this->purchaseDocument,
), (int) auth()->id());
} catch (InvalidStockQuantity) {
$this->addError('purchaseQuantity', __('inventory.errors.quantity'));
return;
} catch (InvalidStockCost) {
$this->addError(trim($this->purchaseTotal) !== '' ? 'purchaseTotal' : 'purchaseUnitPrice', __('inventory.errors.cost'));
return;
} catch (InvalidStockDay) {
$this->addError('purchaseDay', __('inventory.errors.day'));
return;
} catch (StockItemNotFound) {
abort(404);
}
$this->refreshItem();
$this->message = __('inventory.purchase.saved', [
'quantity' => $this->quantity((int) round((float) str_replace(',', '.', $this->purchaseQuantity) * 1000), $this->item->unit),
'balance' => $this->quantity($this->item->balanceMilli, $this->item->unit),
'cost' => $this->unitCost($this->item->averageCostHundredths),
]);
$this->reset('purchaseQuantity', 'purchaseTotal', 'purchaseUnitPrice', 'purchaseDocument');
$this->js("document.getElementById('item-status')?.focus()");
}
public function recordWriteOff(RecordStockWriteOff $recordWriteOff): void
{
$this->authorize('inventory.manage');
$this->resetErrorBag();
try {
$result = $recordWriteOff->execute(new StockUseData($this->itemId, $this->writeOffQuantity, reason: $this->writeOffReason), (int) auth()->id());
} catch (InvalidStockQuantity) {
$this->addError('writeOffQuantity', __('inventory.errors.quantity'));
return;
} catch (StockReasonRequired) {
$this->addError('writeOffReason', __('inventory.errors.reason'));
return;
} catch (StockItemNotFound) {
abort(404);
}
$this->refreshItem();
$this->message = __('inventory.write_off.saved', [
'quantity' => $this->quantity($result->quantityMilli, $this->item->unit),
'balance' => $this->quantity($result->balanceMilli, $this->item->unit),
]);
$this->reset('writeOffQuantity', 'writeOffReason');
$this->js("document.getElementById('item-status')?.focus()");
}
public function recordUse(RecordStockUse $recordUse): void
{
$this->authorize('inventory.record-use');
$this->resetErrorBag();
try {
$result = $recordUse->execute(new StockUseData($this->itemId, $this->useQuantity, reason: $this->useReason), (int) auth()->id());
} catch (InvalidStockQuantity) {
$this->addError('useQuantity', __('inventory.errors.quantity'));
return;
} catch (StockReasonRequired) {
$this->addError('useReason', __('inventory.errors.reason'));
return;
} catch (StockItemInactive) {
$this->addError('useQuantity', __('inventory.errors.inactive'));
return;
} catch (StockItemNotFound) {
abort(404);
}
$this->refreshItem();
$this->message = __('inventory.use.saved', [
'quantity' => $this->quantity($result->quantityMilli, $this->item->unit),
'balance' => $this->quantity($result->balanceMilli, $this->item->unit),
]);
$this->reset('useQuantity', 'useReason');
$this->js("document.getElementById('item-status')?.focus()");
}
public function confirmReverse(int $movementId): void
{
$movement = $this->movement($movementId);
abort_unless($this->mayReverse($movement), 403);
$this->reverseMovementId = $movementId;
$this->js("document.getElementById('reverse-dialog').showModal()");
}
public function reverse(ReverseStockMovement $reverseMovement): void
{
$movement = $this->movement((int) $this->reverseMovementId);
abort_unless($this->mayReverse($movement), 403);
try {
$reverseMovement->execute($movement->id, (int) auth()->id(), Gate::allows('inventory.reverse-any'));
$this->refreshItem();
$this->message = __('inventory.item.reversed', ['balance' => $this->quantity($this->item->balanceMilli, $this->item->unit)]);
} catch (StockMovementNotFound) {
$this->message = __('inventory.errors.not_found');
} catch (StockMovementAlreadyReversed) {
$this->message = __('inventory.errors.already_reversed');
} catch (StockMovementNotReversible) {
$this->message = __('inventory.errors.not_reversible');
} catch (StockReversalNotAllowed) {
$this->message = __('inventory.errors.reversal_not_allowed');
}
$this->reverseMovementId = null;
$this->refreshItem();
$this->js("document.getElementById('reverse-dialog').close(); document.getElementById('item-status').focus()");
}
public function toggleActive(SetStockItemActive $setActive): void
{
$this->authorize('inventory.manage');
$active = ! $this->item->isActive;
$setActive->execute($this->itemId, $active);
$this->refreshItem();
$this->message = __($active ? 'inventory.item.activated' : 'inventory.item.deactivated');
}
public function mayReverse(StockMovementSummary $movement): bool
{
if (! $movement->canBeReversed()) {
return false;
}
if (Gate::allows('inventory.reverse-any')) {
return true;
}
return Gate::allows('inventory.record-use')
&& $movement->kind->value === 'consumption'
&& $movement->userId === (int) auth()->id()
&& $movement->occurredOn === app(Clock::class)->today()->format('Y-m-d');
}
public function targetText(StockMovementSummary $movement): string
{
$parts = [];
if ($movement->taskId !== null) {
$parts[] = __('inventory.item.target_task', ['id' => $movement->taskId]);
}
if ($movement->machineId !== null) {
$parts[] = __('inventory.item.target_machine', ['id' => $movement->machineId]);
}
if ($movement->orderLineId !== null) {
$parts[] = __('inventory.item.target_order');
}
if ($movement->maintenanceRecordId !== null) {
$parts[] = __('inventory.item.target_maintenance');
}
if ($movement->inventoryCountId !== null) {
$parts[] = __('inventory.item.target_count', ['id' => $movement->inventoryCountId]);
}
if ($movement->supplier !== null) {
$parts[] = $movement->supplier;
}
if ($movement->documentNumber !== null) {
$parts[] = __('inventory.item.document', ['number' => $movement->documentNumber]);
}
if ($movement->reason !== null) {
$parts[] = $movement->reason;
}
if ($movement->reversesMovementId !== null) {
$parts[] = __('inventory.item.reverses', ['number' => $movement->reversesMovementId]);
}
return $parts === [] ? '–' : implode(', ', $parts);
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function headers(): array
{
$headers = [
['index' => 'time', 'label' => __('inventory.columns.time'), 'sortable' => false],
['index' => 'kind', 'label' => __('inventory.columns.kind'), 'sortable' => false],
['index' => 'quantity', 'label' => __('inventory.columns.quantity'), 'sortable' => false, 'align' => 'right'],
['index' => 'balance', 'label' => __('inventory.columns.balance_after'), 'sortable' => false, 'align' => 'right'],
['index' => 'user', 'label' => __('inventory.columns.user'), 'sortable' => false],
['index' => 'target', 'label' => __('inventory.columns.target'), 'sortable' => false],
];
if (Gate::allows('inventory.see-value')) {
$headers[] = ['index' => 'value', 'label' => __('inventory.columns.value'), 'sortable' => false, 'align' => 'right'];
}
$headers[] = ['index' => 'actions', 'label' => __('inventory.columns.actions'), 'sortable' => false];
return $headers;
}
public function render(): mixed
{
return $this->view()->title($this->item->name);
}
private function movement(int $movementId): StockMovementSummary
{
$movement = app(StockQueries::class)->findMovement($movementId);
abort_if($movement === null || $movement->itemId !== $this->itemId, 404);
return $movement;
}
private function refreshItem(): void
{
unset($this->item, $this->movements);
}
};
?>
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
@php($item = $this->item)
<div class="flex flex-wrap items-start gap-4">
@if ($item->hasImage)
<img src="{{ route('inventory.items.image', [$item->id, 'thumbnail']) }}" alt="{{ __('inventory.item.image_alt', ['name' => $item->name]) }}" class="size-24 rounded-md border border-zinc-300 object-cover dark:border-zinc-600" />
@endif
<div class="min-w-0 flex-1 space-y-2">
<p class="text-sm"><x-link :href="route('inventory.index')" navigate>{{ __('inventory.groups.back') }}</x-link></p>
<h1 class="text-2xl font-semibold break-words">{{ $item->name }}</h1>
<x-inventory.stock-status :item="$item" />
@can('inventory.manage')
<div class="flex flex-wrap gap-2">
<x-button :href="route('inventory.items.edit', $item->id)" wire:navigate sm icon="pencil" :text="__('inventory.item.edit')" />
<x-button wire:click="toggleActive" subtle color="black" sm :icon="$item->isActive ? 'archive-box-x-mark' : 'archive-box-arrow-down'" :text="$item->isActive ? __('inventory.item.deactivate') : __('inventory.item.activate')" />
</div>
@endcan
</div>
</div>
<p id="item-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $message }}</p>
<section aria-labelledby="details-heading" class="space-y-3">
<h2 id="details-heading" class="text-lg font-semibold">{{ __('inventory.item.details') }}</h2>
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-2 lg:grid-cols-3">
<div>
<dt class="font-medium">{{ __('inventory.item.balance') }}</dt>
<dd class="text-lg font-semibold">{{ $this->quantity($item->balanceMilli, $item->unit) }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.columns.group') }}</dt>
<dd>{{ $item->groupName }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.columns.reorder_level') }}</dt>
<dd>{{ $item->reorderLevelMilli === null ? '–' : $this->quantity($item->reorderLevelMilli, $item->unit) }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.form.code') }}</dt>
<dd>{{ $item->code ?? '–' }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.form.supplier') }}</dt>
<dd>{{ $item->supplier ?? '–' }}</dd>
</div>
@can('inventory.see-value')
<div>
<dt class="font-medium">{{ __('inventory.columns.average_cost') }}</dt>
<dd>{{ $this->unitCost($item->averageCostHundredths) }} / {{ __('inventory.units.'.$item->unit->value) }}</dd>
</div>
<div>
<dt class="font-medium">{{ __('inventory.columns.value') }}</dt>
<dd>{{ $this->money($item->valueCents) }}</dd>
</div>
@endcan
</dl>
@if ($item->isNegative())
<p class="flex items-start gap-2 text-sm font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
{{ __('inventory.use.negative_warning') }}
</p>
@endif
</section>
@php($unitLabel = __('inventory.units.'.$item->unit->value))
<div class="grid gap-6 lg:grid-cols-2">
@can('inventory.manage')
<section aria-labelledby="purchase-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="purchase-heading" class="text-lg font-semibold">{{ __('inventory.purchase.title') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.purchase.intro') }}</p>
<form wire:submit="recordPurchase" class="space-y-4" novalidate>
<x-input id="purchase-day" wire:model="purchaseDay" type="date" :label="__('inventory.purchase.day')" required />
<x-input id="purchase-quantity" wire:model="purchaseQuantity" inputmode="decimal" :label="__('inventory.purchase.quantity', ['unit' => $unitLabel])" autocomplete="off" />
<x-input id="purchase-total" wire:model="purchaseTotal" inputmode="decimal" :label="__('inventory.purchase.total_price')" autocomplete="off" />
<x-input id="purchase-unit-price" wire:model="purchaseUnitPrice" inputmode="decimal" :label="__('inventory.purchase.unit_price', ['unit' => $unitLabel])" :hint="__('inventory.purchase.unit_price_hint')" autocomplete="off" />
<x-input id="purchase-supplier" wire:model="purchaseSupplier" :label="__('inventory.purchase.supplier')" autocomplete="off" maxlength="255" />
<x-input id="purchase-document" wire:model="purchaseDocument" :label="__('inventory.purchase.document_number')" autocomplete="off" maxlength="255" />
<x-button submit icon="truck" :text="__('inventory.purchase.save')" />
</form>
</section>
<section aria-labelledby="write-off-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="write-off-heading" class="text-lg font-semibold">{{ __('inventory.write_off.title') }}</h2>
<form wire:submit="recordWriteOff" class="space-y-4" novalidate>
<x-input id="write-off-quantity" wire:model="writeOffQuantity" inputmode="decimal" :label="__('inventory.write_off.quantity', ['unit' => $unitLabel])" autocomplete="off" />
<x-input id="write-off-reason" wire:model="writeOffReason" :label="__('inventory.write_off.reason')" :hint="__('inventory.write_off.reason_hint')" autocomplete="off" maxlength="255" />
<x-button submit icon="trash" :text="__('inventory.write_off.save')" />
</form>
</section>
@endcan
@if ($item->isActive)
@can('inventory.record-use')
<section aria-labelledby="use-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="use-heading" class="text-lg font-semibold">{{ __('inventory.use.title') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.use.intro') }}</p>
<form wire:submit="recordUse" class="space-y-4" novalidate>
<x-input id="use-quantity" wire:model="useQuantity" inputmode="decimal" :label="__('inventory.use.quantity', ['unit' => $unitLabel])" autocomplete="off" />
<x-input id="use-reason" wire:model="useReason" :label="__('inventory.use.reason')" autocomplete="off" maxlength="255" />
<x-button submit icon="minus-circle" :text="__('inventory.use.save')" />
</form>
</section>
@endcan
@else
<p class="text-sm">{{ __('inventory.item.inactive_note') }}</p>
@endif
</div>
<section aria-labelledby="history-heading" class="space-y-3">
<h2 id="history-heading" class="text-lg font-semibold">{{ __('inventory.item.history') }}</h2>
@if ($this->movements === [])
<p class="text-sm">{{ __('inventory.item.history_none') }}</p>
@else
@if (count($this->movements) >= $this::HISTORY_LIMIT)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.item.history_limit', ['count' => $this::HISTORY_LIMIT]) }}</p>
@endif
<x-table :headers="$this->headers()" :rows="$this->movements">
@interact('column_time', $movement)
<span class="whitespace-nowrap">{{ $this->dateLabel($movement->recordedAt) }}</span>
@if ($movement->occurredOn !== substr($movement->recordedAt, 0, 10))
<span class="block text-xs">{{ $this->dateLabel($movement->occurredOn) }}</span>
@endif
@endinteract
@interact('column_kind', $movement)
{{ __('inventory.kinds.'.$movement->kind->value) }}
@if ($movement->reversedByMovementId !== null)
<span class="block text-xs">{{ __('inventory.item.reversed_by', ['number' => $movement->reversedByMovementId]) }}</span>
@endif
@endinteract
@interact('column_quantity', $movement)
<span class="whitespace-nowrap">{{ ($movement->quantityMilli > 0 ? '+' : '').$this->quantity($movement->quantityMilli) }}</span>
@endinteract
@interact('column_balance', $movement)
<span class="whitespace-nowrap">{{ $this->quantity($movement->balanceAfterMilli) }}</span>
@endinteract
@interact('column_user', $movement)
{{ $movement->userName }}
@endinteract
@interact('column_target', $movement)
<span class="whitespace-normal">{{ $this->targetText($movement) }}</span>
@endinteract
@interact('column_value', $movement)
<span class="whitespace-nowrap">{{ $this->money($movement->valueCents) }}</span>
@endinteract
@interact('column_actions', $movement)
@if ($this->mayReverse($movement))
<x-button
wire:click="confirmReverse({{ $movement->id }})"
subtle
color="black"
sm
icon="arrow-uturn-left"
:text="__('inventory.item.reverse')"
:aria-label="__('inventory.item.reverse_named', ['kind' => __('inventory.kinds.'.$movement->kind->value), 'quantity' => $this->quantity($movement->quantityMilli), 'time' => $this->dateLabel($movement->recordedAt)])"
/>
@endif
@endinteract
</x-table>
@endif
</section>
<x-confirm-dialog id="reverse-dialog" :title="__('inventory.item.reverse_title')">
@php($reverseMovement = $reverseMovementId === null ? null : collect($this->movements)->firstWhere('id', $reverseMovementId))
@if ($reverseMovement !== null)
<p>{{ __('inventory.item.reverse_text', ['kind' => __('inventory.kinds.'.$reverseMovement->kind->value), 'quantity' => $this->quantity($reverseMovement->quantityMilli, $item->unit)]) }}</p>
@endif
<x-slot:actions>
<x-button wire:click="reverse" color="red" :text="__('inventory.item.reverse_confirm')" />
</x-slot:actions>
</x-confirm-dialog>
</div>
@@ -0,0 +1,23 @@
<?php
use App\Modules\Inventory\Presentation\Http\Controllers\ShowStockItemImage;
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:inventory.view'])
->prefix('inventory')
->name('inventory.')
->group(function () {
Route::livewire('/', 'inventory::index')->name('index');
Route::get('/items/{item}/image/{size}', ShowStockItemImage::class)
->whereNumber('item')
->whereIn('size', ['full', 'thumbnail'])
->name('items.image');
Route::middleware('can:inventory.manage')->group(function () {
Route::livewire('/groups', 'inventory::groups')->name('groups');
Route::livewire('/items/create', 'inventory::item-form')->name('items.create');
Route::livewire('/items/{item}/edit', 'inventory::item-form')->whereNumber('item')->name('items.edit');
});
Route::livewire('/items/{item}', 'inventory::item')->whereNumber('item')->name('items.show');
});
@@ -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);
try {
$full = $this->scaled($image, self::MAX_SIZE);
$thumbnail = $this->scaled($image, self::THUMBNAIL_SIZE);
$versions = $this->resizer->jpegVersions($uploadedFilePath, [self::MAX_SIZE, self::THUMBNAIL_SIZE]) ?? throw new InvalidTaskImage;
[$full, $thumbnail] = $versions;
$name = 'task-images/'.$taskId.'/'.Str::uuid()->toString();
$stored = new StoredTaskImage($name.'.jpg', $name.'-thumb.jpg', imagesx($full), imagesy($full));
$stored = new StoredTaskImage($name.'.jpg', $name.'-thumb.jpg', $full['width'], $full['height']);
Storage::disk(self::DISK)->put($stored->path, $this->jpeg($full));
Storage::disk(self::DISK)->put($stored->thumbnailPath, $this->jpeg($thumbnail));
Storage::disk(self::DISK)->put($stored->path, $full['bytes']);
Storage::disk(self::DISK)->put($stored->thumbnailPath, $thumbnail['bytes']);
return $stored;
} finally {
imagedestroy($image);
}
}
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();
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Application\Contracts;
/**
* Turns an uploaded image into upright, downscaled JPEGs without metadata
* (no location), for task images and stock item images.
*/
interface ImageResizer
{
/**
* JPEG versions of the image whose longer side is at most each of the
* given sizes, or null when the file is not a readable image.
*
* @param list<int> $maxSizes
* @return list<array{bytes: string, width: int, height: int}>|null
*/
public function jpegVersions(string $path, array $maxSizes): ?array;
}
@@ -0,0 +1,141 @@
<?php
namespace App\Modules\Shared\Infrastructure\Images;
use App\Modules\Shared\Application\Contracts\ImageResizer;
use GdImage;
/**
* Turns an uploaded image into upright, downscaled JPEGs with GD. Saving
* again as JPEG leaves out all metadata (such as the location) and anything
* else embedded in the upload. Used for task images and stock item images.
*/
class GdImageResizer implements ImageResizer
{
/**
* Larger images would not fit in memory when decoded.
*/
private const int MAX_PIXELS = 50_000_000;
private const int QUALITY = 82;
/**
* JPEG versions of the image whose longer side is at most each of the
* given sizes, or null when the file is not a readable image.
*
* @param list<int> $maxSizes
* @return list<array{bytes: string, width: int, height: int}>|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();
}
}
@@ -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
+1
View File
@@ -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'],
+2
View File
@@ -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,
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace Database\Factories;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<StockItemModel>
*/
class StockItemFactory extends Factory
{
protected $model = StockItemModel::class;
/**
* @return array<string, mixed>
*/
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]);
}
}
@@ -0,0 +1,26 @@
<?php
namespace Database\Factories;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<StockItemGroupModel>
*/
class StockItemGroupFactory extends Factory
{
protected $model = StockItemGroupModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->unique()->words(2, true),
'sort_order' => fake()->unique()->numberBetween(1, 100000),
'is_active' => true,
];
}
}
@@ -0,0 +1,78 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Stock accounting (spec 19.1–19.2): item groups, items with their
* moving average cost, and movements, whose sum is an item's balance.
* Quantities are in thousandths of the unit, unit costs in hundredths
* of a cent and values in cents. The links to machines, quick sale
* order lines, maintenance records and stock counts get their foreign
* keys with those tables.
*/
public function up(): void
{
Schema::create('stock_item_groups', function (Blueprint $table) {
$table->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');
}
};
+189
View File
@@ -0,0 +1,189 @@
<?php
return [
'units' => [
'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.',
],
];
+3
View File
@@ -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',
+189
View File
@@ -0,0 +1,189 @@
<?php
return [
'units' => [
'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.',
],
];
+3
View File
@@ -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',
@@ -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'])
<span {{ $attributes->class('inline-flex flex-wrap items-center gap-x-2 gap-y-1') }}>
@if ($item->isNegative())
<span class="inline-flex items-center gap-1 font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />
{{ __('inventory.status.negative') }}
</span>
@elseif ($item->needsReorder())
<span class="inline-flex items-center gap-1 font-medium text-amber-800 dark:text-amber-300">
<x-icon name="shopping-cart" class="size-4" aria-hidden="true" />
{{ __('inventory.status.reorder') }}
</span>
@else
<span class="inline-flex items-center gap-1">
<x-icon name="check-circle" class="size-4" aria-hidden="true" />
{{ __('inventory.status.ok') }}
</span>
@endif
@unless ($item->isActive)
<span class="inline-flex items-center gap-1">
<x-icon name="archive-box-x-mark" class="size-4" aria-hidden="true" />
{{ __('inventory.status.inactive') }}
</span>
@endunless
</span>
@@ -0,0 +1,63 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->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');
});
@@ -0,0 +1,216 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->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();
});
@@ -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)
@@ -0,0 +1,77 @@
<?php
use App\Modules\Inventory\Domain\Entities\StockItem;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\Services\StockSearch;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
it('parses and formats quantities with three decimals', function () {
expect(StockQuantity::parsePositive('2,5')->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();
});