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,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);
});
}
}