81 lines
2.4 KiB
PHP
81 lines
2.4 KiB
PHP
<?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);
|
|
});
|
|
}
|
|
}
|